/* uart/uart.c
 *
 * UART Interface Driver
 *
 * Copyright (c) 2011 by BKIT4U <www.bkit4u.com>
 * Author: BS135 <thanhhai135@gmail.com>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General  Public  License
 * as published by the Free Software Foundation;version 2 or 2.1
 * of the License. This license can be found at
 *                           http://www.gnu.org/licenses/gpl.txt
 *
 * Target MCU	: Atmel AVR series
 * Editor Tabs	: 4
 */


#include <stdint.h>
#include <avr/io.h>
#include "uart.h"

/*
 * Initialization UART operation mode
 */
void uart_init(){
	// USART initialization
	// Communication Parameters: 8 Data, 1 Stop, No Parity
	// USART Receiver: On
	// USART Transmitter: On
	// USART Mode: Asynchronous
	// USART Baud Rate: 9600

	uint16_t _ubrr;

	UCSRA = 0x00;
	UCSRB =_BV(TXEN)|_BV(RXEN);	//0001 1000	
								//Receiver Enable
								//Transmitter Enable
	UCSRC = _BV(URSEL)|_BV(UCSZ1)|_BV(UCSZ0);	//1000 0110
												//frame: 8 Data, 1 Stop, No Parity
												//Asynchronous mode
	_ubrr = ((F_CPU/16L)/UART_BAUD_RATE) - 1;
	UBRRH = _ubrr>>8;
	UBRRL = _ubrr;	//Baud Rate
	//UBRRH=0x00;
	//UBRRL=0x4D;
	
}

/*
 * Transmit a byte through UART bus
 */
void uart_transmit_byte(char c)
{ 
	loop_until_bit_is_set(UCSRA, UDRE);
	UDR = c;
}


/*
 * Receive a byte from UART bus
 */
int uart_receive_byte()
{
	loop_until_bit_is_set(UCSRA, RXC);
	if(UCSRA & (_BV(FE)|_BV(DOR)|_BV(PE)))
		return -1; //error
	return UDR;
} 


    





